import NProgress from 'nprogress'
import { Router } from 'vue-router'
import { useUserStoreWithOut } from '@/store/modules/user/src'
import { oidcRouter } from '@/tools'

export function setupPermission(router: Router) {
  // 白名单路由
  const whiteList = ['/login', '/err', '/err/401', '/err/404']
  oidcRouter.forEach((item: any) => {
    whiteList.push(item.path)
  })

  router.beforeEach(async (to, from, next) => {
    NProgress.start()

    const userStore = useUserStoreWithOut()
    const tenantId = userStore.getTenantId ?? 0
    if (tenantId) {
      // 判断是否有权限 todo
      if (to.matched.length === 0) {
        from.path ? next(from.path) : next('/err/404')
      } else {
        next()
      }
    } else {
      // 未登录可以访问白名单页面
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  })

  router.afterEach(() => {
    NProgress.done()
  })
}
